class MilestonesController < InnerApplicationController

  def index
    @milestones = @project.milestones
    
    @late = @project.milestones.late.all(:order => :due)
    
    @scheduled = @project.milestones.pending.all(:order => :due) - @late
    
    @completed = @project.milestones.completed.all(:order => :due)
    
    @unscheduled = @project.milestones.all(:order => :due) - @late - @scheduled - @completed
    
    @upcoming = @project.milestones.pending.all(:include => [:activities, :project],
                                                :order => :due).group_by { |milestone| milestone.due.beginning_of_month }
                                                
    render :layout => "one_column" unless @milestones.size > 0
  end
  
  def show
    @milestone = @project.milestones.find(params[:id], :include => [:activities, :comments])
    
    @completed = @milestone.activities.all(:order => :created_at).delete_if {|activity| activity.completed_at.nil?}
    @activities_by_user = @milestone.activities.all(:order => ["responsible_id, completed_at, created_at"]).group_by {|activity| activity.responsible}
  end
  
  def new
    @milestone = @project.milestones.new
    
    render :layout => "one_column"
  end
  
  def edit
    @milestone = @project.milestones.find(params[:id])
    
    render :layout => "one_column"
  end
  
  def create
    @milestone = @project.milestones.new(params[:milestone])
    
    if @milestone.save
      flash[:success] = I18n.t :created, :scope => [:milestone, :messages, :success]
      redirect_to project_milestone_url(@project, @milestone)
    else
      render :action => "new"
    end
  end
  
  def update
    @milestone = @project.milestones.find(params[:id])
    
    if @milestone.update_attributes(params[:milestone])
      flash[:success] = I18n.t :updated, :scope => [:milestone, :messages, :success]
      redirect_to project_milestone_path(@project, @milestone)
    else
      render :action => "edit"
    end
  end
  
  def destroy
    @milestone = @project.milestones.find(params[:id])
    @milestone.destroy
  end
end
